package asia.hymsk.spring.service.information.email.impl;

import asia.hymsk.spring.service.information.email.MailClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author 花于陌上开
 */
@Component
public class MailClientImpl implements MailClient {
    private final JavaMailSender mailSender;
    private final String from;


    public MailClientImpl(JavaMailSender mailSender, @Value("${spring.mail.username}") String from) {
        this.mailSender = mailSender;
        this.from = from;
    }

    /**
     * 发送邮件
     *
     * @param to      收件方的邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendMail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param email 接收邮箱
     * @param code  验证码
     */
    @Override
    public String sendMessageWithAllNumberCode(String email, String code) {
        sendMail(email, "验证码邮件", String.format("您的验证码：%s(动态验证码)，有效期15分钟 ，请勿将验证码告诉他人。", code));
        return "验证码邮件发送成功";
    }
}